package com.wfuhui.modules.jieyue.api;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wfuhui.common.utils.NumberUtil;
import com.wfuhui.modules.jieyue.entity.JieyueEntity;
import com.wfuhui.modules.jieyue.service.JieyueService;
import com.wfuhui.modules.member.entity.MemberEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.wfuhui.common.utils.DateUtils;
import com.wfuhui.common.utils.R;
import com.wfuhui.modules.book.entity.BookEntity;
import com.wfuhui.modules.book.service.BookService;
import com.wfuhui.modules.member.service.MemberService;
import com.wfuhui.modules.order.entity.OrderBookEntity;
import com.wfuhui.modules.order.entity.OrderEntity;
import com.wfuhui.modules.order.service.OrderService;

/**
 * 借阅接口
 * @author 2803180149
 *
 */
@RestController
@RequestMapping("/api/jieyue")
public class ApiJieyueController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private BookService bookService;

	@Autowired
	private JieyueService jieyueService;

	@Autowired
	private MemberService memberService;
	
    @GetMapping("list")
    public R getJieyueList(@RequestAttribute Long userId, Integer status){
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("orderStatus", status);
    	params.put("memberId", userId);
    	List<JieyueEntity> orderList = jieyueService.queryList(params);
        return R.ok().put("orderList", orderList);
    }

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public R save(@RequestAttribute("userId") Long userId,@RequestBody JieyueEntity jieyue){
		MemberEntity member = memberService.queryObject(userId);
		if( member== null || member.getDeposit() == null ||  member.getDeposit().compareTo(new BigDecimal(0)) < 1) {
			return R.error("您还未交押金");
		}

		jieyue.setOrderNum(NumberUtil.getOrderNumber());
		jieyue.setCreateTime(new Date());
		jieyue.setMemberId(userId);
		jieyue.setOrderStatus(1);
		jieyue.setStartDate(new Date());
		jieyueService.save(jieyue);
		return R.ok();
	}

    @GetMapping("detail")
    public R detail(Integer id) {
		JieyueEntity order = jieyueService.queryObject(id);
    	return R.ok().put("order", order);
    }
    
    @GetMapping("cancel")
    public R cancel(Integer id) {
		JieyueEntity order = new JieyueEntity();
    	order.setOrderStatus(0);
    	order.setId(id);
		jieyueService.update(order);
    	return R.ok();
    }

	/**
	 * 归还
	 */
	@RequestMapping("/returnBook/{jieyueId}")
	public R returnBook(@PathVariable("jieyueId")Integer orderId) {
		JieyueEntity order = new JieyueEntity();
		order.setId(orderId);
		order.setOrderStatus(2);
		order.setEndDate(new Date());
		jieyueService.returnBook(order);
		return R.ok();
	}

}
